package com.orange.common.ktx

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner

/**
 * 参考 Animator.doOnCancel {  }
 * Lifecycle扩展
 */

inline fun Lifecycle.doOnDestroy(crossinline action: () -> Unit = {}) {
    addListener(onDestroy = action)
}

inline fun Lifecycle.addListener(
    crossinline onCreate: () -> Unit = {},
    crossinline onStart: () -> Unit = {},
    crossinline onResume: () -> Unit = {},
    crossinline onPause: () -> Unit = {},
    crossinline onStop: () -> Unit = {},
    crossinline onDestroy: () -> Unit = {},
    crossinline onAny: () -> Unit = {}
) {
    val observer = object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            when (event) {
                Lifecycle.Event.ON_CREATE -> {
                    onCreate()
                }

                Lifecycle.Event.ON_START -> {
                    onStart()
                }

                Lifecycle.Event.ON_RESUME -> {
                    onResume()
                }

                Lifecycle.Event.ON_PAUSE -> {
                    onPause()
                }

                Lifecycle.Event.ON_STOP -> {
                    onStop()
                }

                Lifecycle.Event.ON_DESTROY -> {
                    removeObserver(this)
                    onDestroy()
                }

                Lifecycle.Event.ON_ANY -> {
                    onAny()
                }
            }
        }
    }
    addObserver(observer)
}
